//
//  NetWorkTool.swift
//  OpticalSplitterBox
//
//  Created by 陈志勇 on 2018/6/26.
//  Copyright © 2018年 makepower. All rights reserved.
//

import Alamofire
import SVProgressHUD
import HandyJSON

enum MethodType {
    case get
    case post
}

struct ResponseInfo<T: HandyJSON>: HandyJSON {
    var race_list: ResponseRaceList<T>?
    
}

struct ResponseRaceDetail: HandyJSON {
    var message: [Message]?
}

struct ResponseRaceList<T: HandyJSON>: HandyJSON {
    var first_get_time: String?
    var next_page: Int?
    var list: [T]?
}

class NetWorkTool {
    
    struct BaseResponse: HandyJSON {
        var status: Int?
        var ret: Int?
        var data: ResponseData?
        var msg: String?
    }
    
    struct ResponseData: HandyJSON {
        var code: Int?
        var info: [String:Any]?
        var version: String?
        var msg: String?
        var time: Double?
    }
    
    
    
    
    static let shared: NetWorkTool = {
        let tool = NetWorkTool()
        return tool
    }()
    
    func request(methodType: MethodType, URLString: String, parameters: [String : Any], failed: (() -> ())? = nil, finished: @escaping ((_ result: String, _ date: Date) -> ())) {
        print(URLString)
        let method = methodType == .get ? HTTPMethod.get : HTTPMethod.post
        Alamofire.request(URLString, method: method, parameters: parameters).validate().responseString(queue: nil, encoding: String.Encoding.utf8, completionHandler: { (response) in
            
            var date = Date()
            if let header = response.response?.allHeaderFields {
                let dateStr = header["Date"] as! String
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "EEE, d MMM yyyy HH:mm:ss zzz"
                date = dateFormatter.date(from: dateStr) ?? Date()
            }
            
            switch response.result {
            case .success(_):
                if let jsonString = response.result.value {
                    print(jsonString)
                    finished(jsonString, date)
                }
            case .failure(_):
                if let failed = failed{
                    failed()
                }
                print("请求失败, \(response.error!)")
                SVProgressHUD.showInfo(withStatus: "网络出错：\(response.response?.statusCode ?? 9999)")
            }
        })
    }
    
}

extension NetWorkTool {
    func loadRaceList(finished : @escaping ((_ baseResponse: BaseResponse)->())) {
        let urlStr = "http://football.dooksport.com/api.php?s=Race/getRaceList/cate_id/1/p/0/"
        request(methodType: .get, URLString: urlStr, parameters: [:]) { (jsonString, _) in
            if let base = BaseResponse.deserialize(from: jsonString){
                finished(base)
            }
        }
    }
    
    func loadtScheduleList(finished : @escaping ((_ baseResponse: BaseResponse)->())) {
        let urlStr = "http://football.dooksport.com/api.php?s=RaceInteract/getScheduleList/cate_id/1/p/0/"
        request(methodType: .get, URLString: urlStr, parameters: [:]) { (jsonString, _) in
            if let base = BaseResponse.deserialize(from: jsonString){
                finished(base)
            }
        }
    }
    
    func loadRaceDetail(raceID: String, finished : @escaping ((_ baseResponse: BaseResponse)->())) {
        let urlStr = "http://football.dooksport.com/api.php?s=RaceInteract/getOutsList/schedule_id/" + raceID
        request(methodType: .get, URLString: urlStr, parameters: [:]) { (jsonString, _) in
            if let base = BaseResponse.deserialize(from: jsonString){
                finished(base)
            }
        }
    }
}


